#!/usr/bin/env bash

SCRIPT_PATH=$(cd `dirname "$0"`;pwd)
cd "${SCRIPT_PATH}";

IMAGE_VERSION=$(env node --eval="console.log(require('./package.json').version)")
read BASE_VERSION < ./docker/BASE_VERSION
read FAST_BASE_VERSION < ./docker/FAST_BASE_VERSION

IMAGE_TYPE=$1
IMAGE_ARCH=$2


if [ "$IMAGE_TYPE" == "" ];then
    IMAGE_TYPE=fast
fi

if [ "$IMAGE_ARCH" == "" ];then
    IMAGE_ARCH=amd64
fi

if [ "$IMAGE_ARCH" == "amd64" ];then
    IMAGE_TAG="${IMAGE_VERSION}"
    BASE_IMAGE_TAG="${BASE_VERSION}"
    FAST_BASE_IMAGE_TAG="${FAST_BASE_VERSION}"
else 
    BASE_IMAGE_TAG="${BASE_VERSION}-${IMAGE_ARCH}"
    IMAGE_TAG="${IMAGE_VERSION}-${IMAGE_ARCH}"
    FAST_BASE_IMAGE_TAG="${FAST_BASE_VERSION}-${IMAGE_ARCH}"
fi

DOCKER_FILE_PATH="./docker/${IMAGE_ARCH}/"


## 包含nodejs、wkhtmlpdf、chrome所需依赖、jdk
if [ "$IMAGE_TYPE" == "base" ]; then
    echo docker rmi wuxue107/screenshot-api-base:${BASE_IMAGE_TAG}
    docker rmi wuxue107/screenshot-api-base:${BASE_IMAGE_TAG}
    echo docker build -f "${DOCKER_FILE_PATH}Dockerfile-Base" -t wuxue107/screenshot-api-base:${BASE_IMAGE_TAG} .
    docker build -f "${DOCKER_FILE_PATH}Dockerfile-Base" -t wuxue107/screenshot-api-base:${BASE_IMAGE_TAG} .
fi 

## 包含在base镜像的基础上添加: screenshot-api-server的nodejs依赖和puppeteer chrome
if [ "$IMAGE_TYPE" == "fastbase" ]; then
    echo docker rmi wuxue107/screenshot-api-server-fast-base:${FAST_BASE_IMAGE_TAG}
    docker rmi wuxue107/screenshot-api-server-fast-base:${FAST_BASE_IMAGE_TAG}
    echo docker build --build-arg "BASE_IMAGE_TAG=$BASE_IMAGE_TAG" -f "${DOCKER_FILE_PATH}Dockerfile-FastBase" -t wuxue107/screenshot-api-server-fast-base:${FAST_BASE_IMAGE_TAG} .
    docker build --build-arg "BASE_IMAGE_TAG=$BASE_IMAGE_TAG" -f "${DOCKER_FILE_PATH}Dockerfile-FastBase" -t wuxue107/screenshot-api-server-fast-base:${FAST_BASE_IMAGE_TAG} .
fi 

## 在fastbase镜像基础上，将当前screenshot-api-server程序包拷贝进去
if [ "$IMAGE_TYPE" == "fast" ]; then
    git archive --format=tar --worktree-attributes --prefix=screenshot-api-server/ -o latest.tar HEAD
    
    docker rmi wuxue107/screenshot-api-server:${IMAGE_TAG}
    echo docker build --build-arg "FAST_BASE_IMAGE_TAG=$FAST_BASE_IMAGE_TAG" -f "${DOCKER_FILE_PATH}Dockerfile-Fast" -t wuxue107/screenshot-api-server:${IMAGE_TAG} .
    docker build --build-arg "FAST_BASE_IMAGE_TAG=$FAST_BASE_IMAGE_TAG" -f "${DOCKER_FILE_PATH}Dockerfile-Fast" -t wuxue107/screenshot-api-server:${IMAGE_TAG} .
    rm -rf latest.tar
    
    if [ "$IMAGE_ARCH" == "amd64" ]; then
        docker rmi wuxue107/screenshot-api-server:latest
        docker tag wuxue107/screenshot-api-server:${IMAGE_TAG} wuxue107/screenshot-api-server:latest
    fi
fi 
